package com.zhentao.equipment.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.equipment.mapper.DeviceMaintenancePlanMapper;
import com.zhentao.equipment.mapper.DeviceStatusLogMapper;
import com.zhentao.pojo.DeviceMaintenancePlan;
import com.zhentao.pojo.DeviceStatusLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 定时任务：
 * 1) 计划到期提醒扫描
 * 2) 离线设备扫描并记录离线日志
 */
@Component
public class DeviceScheduler {

    @Autowired
    private DeviceMaintenancePlanMapper planMapper;

    @Autowired
    private DeviceStatusLogMapper statusLogMapper;

    @Autowired(required = false)
    private StringRedisTemplate redis;

    /** 每天9点扫描近7天内到期但未完成的维护计划（这里只记录日志，实际可对接通知） */
    @Scheduled(cron = "0 0 9 * * ?")
    public void scanDuePlans() {
        LocalDate today = LocalDate.now();
        LocalDate in7 = today.plusDays(7);
        List<DeviceMaintenancePlan> list = planMapper.selectList(new LambdaQueryWrapper<DeviceMaintenancePlan>()
                .between(DeviceMaintenancePlan::getPlanDate, java.sql.Date.valueOf(today), java.sql.Date.valueOf(in7))
                .eq(DeviceMaintenancePlan::getStatus, 1)); // 待执行
        // 这里可以对接消息/邮件/短信；为简单起见暂不实现外发
    }

    /** 每5分钟扫描Redis心跳，发现超时的设备则记录离线日志 */
    @Scheduled(cron = "0 */5 * * * ?")
    public void scanOffline() {
        if (redis == null) return;
        // 这里假设使用 keys 模式；生产建议维护设备列表或使用Scan以避免阻塞
        for (String key : redis.keys("device:online:*")) {
            String ts = redis.opsForValue().get(key);
            if (ts == null) continue;
            long last = Long.parseLong(ts);
            // 超过30分钟无心跳视为离线
            if (System.currentTimeMillis() - last > 30 * 60 * 1000L) {
                Long deviceId = Long.parseLong(key.substring("device:online:".length()));
                DeviceStatusLog log = new DeviceStatusLog();
                log.setDeviceId(deviceId);
                log.setOldStatus(1); // 在线
                log.setNewStatus(2); // 离线
                log.setChangeReason("心跳超时");
                log.setCreateTime(new Date());
                statusLogMapper.insert(log);
                // 可在此触发告警/通知
            }
        }
    }
}





